#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    setWindowTitle("键盘事件测试");
    setAutoFillBackground(true); //

//    QPalette* plet = new QPalette(); //paletee()是this的函数
//    plet->setColor(QPalette::Window, Qt::red);
//    this->setPalette(*plet);

    setMinimumSize(1000, 800);
    setMaximumSize(1000, 800);

    width = size().width();  //获得窗口的长
    height = size().height();  //获得窗口的高

    //QPixmap相当于是画布，先用paiter类画Qpixmap
    //然后再发Qpixmap画入this
    pix = new QPixmap(width, height);


    image = new QImage();
    image->load("C:/Users/2426/Desktop/01.jfif");   //加载的时候要判断是否加载成功

    startx = 30;  //图片的起始位置
    starty = 30;
    step = 30;    //步长


    //qDebug() << QPoint(100, 200);

    drawPixmapFunc();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::drawPixmapFunc()
{
    pix->fill(Qt::green);

    QPainter* painter = new QPainter;
    QPen pen(Qt::DashDotDotLine); //用点画线

    //画出网格出来
    for(int i = step; i < width; i += step)  //竖线
    {
        painter->begin(pix); //画入pix
        painter->setPen(pen);
        painter->drawLine(QPoint(i, 0), QPoint(i, height));
        painter->end();
    }

    for(int j = step; j < height; j = j + step) // 横线
    {
            painter->begin(pix);
            painter->setPen(pen);
            painter->drawLine(QPoint(0,j),QPoint(width,j));
            painter->end();
    }

    painter->begin(pix);
    painter->drawImage(QPoint(startx, starty), *image);  //将这个图片画入pix
    painter->end();
}


void Widget::paintEvent(QPaintEvent* p)
{
    QPainter pt;
    pt.begin(this);  //画在this的类窗口
    pt.drawPixmap(QPoint(0, 0), *pix);
    pt.end();
}


void Widget::keyPressEvent(QKeyEvent* k)
{
//    startx = startx - startx % step;
//    starty = starty - starty % step;

    if(k->key() == Qt::Key_Left)
    {
        startx = startx - step < 0 ? startx : startx - step;
    }
    else if(k->key() == Qt::Key_Right)
    {
        startx = startx + step > width ? startx : startx + step;
    }
    else if(k->key() == Qt::Key_Down)
    {
        starty = starty + step > height ? starty : starty + step;
    }
    else if(k->key() == Qt::Key_Up)
    {
        starty = starty - step < 0 ? starty : starty - step;
    }

    drawPixmapFunc();
    update();
}




